package com.biscuit.page.basicservice.conf.handler;

import com.biscuit.page.basicservice.model.context.TransactionContext;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author biscuit
 * @create 2024年07月22日 20:21
 */
@Slf4j
public class TransactionHandler {

    private static final ThreadLocal<TransactionContext> LOCAL = new ThreadLocal<>();

    public static String getTxId() {
        BaseExceptionUtil.throwException(Objects.nonNull(LOCAL.get()) && StringUtil.isNotBlank(LOCAL.get().getTxId()), "暂未开启事务");
        return LOCAL.get().getTxId();
    }

    // 是否开启事务
    public static boolean isOpenTx() {
        return Objects.nonNull(LOCAL.get()) && StringUtil.isNotBlank(LOCAL.get().getTxId());
    }

    public static void setTxId(String txId) {
        TransactionContext context = new TransactionContext();
        LOCAL.set(context);
        context.setTxId(txId);
    }

    public static void clear() {
        LOCAL.remove();
    }

}
